﻿using System;
using System.Collections.Generic;
using System.Data.Common;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using QuickORM.BLL;
using QuickORM.Entity;

public partial class Manage_WebPages_UserInfo_Function2Role : BasePage
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            string RoleID = Request.QueryString["id"];
            ViewState["RoleID"] = RoleID;
            //  txtRoleName.Text = global.GetRolName(RoleID);
            DataTable dt = new DataTable();


            dt = BLLFactory<T_Function2RoleManager>.Instance.FindToDataTable("RoleID='" + RoleID + "'");
            Session["dt"] = dt;
            LoadMenu(tvMenu);
            loadMenuCheckbox();//初始化选中的节点
        }
    }
    #region 初始化功能树
    private void LoadMenu(TreeView treeView)
    {
        treeView.Nodes.Clear();
        //ds = bll.GetList("pid=0");
        List<T_Sys_Menu> dt = BLLFactory<T_Sys_MenuManager>.Instance.Find("pid=0", "order by id");
        foreach (T_Sys_Menu rows in dt)
        {
            //添加根节点信息
            TreeNode treeNodeParent = CreatTreeNode(Convert.ToString(rows.Name), Convert.ToString(rows.Id), "", "");
            treeView.Nodes.Add(treeNodeParent);
            DataTable table = BLLFactory<T_Sys_MenuManager>.Instance.FindToDataTable("pid='" + treeNodeParent.Value + "'");// GNGLBLL.GetSSO_FUNCTIONByParentId(treeNodeParent.Value);
            System.Data.DataView dv = new System.Data.DataView(table);
            foreach (DataRowView row in dv)
            {
                string FParentId = Convert.ToString(row["id"]);
                string FName = Convert.ToString(row["name"]);
                TreeNode treeNodeChilde = CreatTreeNode(FName, FParentId, "", "");
                //使用递归实现树型菜单的显示
                ViewState["key"] = 1;
                RecursionMenu(FParentId, treeNodeChilde);
                AddTreeNode(treeNodeParent, treeNodeChilde);
            }
        }
    }
    #endregion

    #region 使用递归实现树
    public void RecursionMenu(string FParentId, TreeNode treeNode)
    {
        Session["treeNode"] = treeNode;
        DataTable dt = BLLFactory<T_Sys_MenuManager>.Instance.FindToDataTable("pid='" + FParentId + "'");// GNGLBLL.GetSSO_FUNCTIONByParentId(FParentId);
        if (dt.Rows.Count != 0)
        {
            System.Data.DataView dv = new System.Data.DataView(dt);
            foreach (DataRowView row in dv)
            {
                string FParentIdChild = Convert.ToString(row["id"]);
                string FName = Convert.ToString(row["name"]);
                TreeNode treeNodeChile = CreatTreeNode(FName, FParentIdChild, "", "");
                RecursionMenu(FParentIdChild, treeNodeChile);
                AddTreeNode(treeNode, treeNodeChile);
            }
        }
    }
    #endregion

    #region 添加子节点到父节点上
    public void AddTreeNode(System.Web.UI.WebControls.TreeNode parentNode, TreeNode ChildTreeNode)
    {
        parentNode.ChildNodes.Add(ChildTreeNode);
    }
    #endregion

    #region 绑定节点信息
    public TreeNode CreatTreeNode(string strTest, string functionId, string strUrl, string img)
    {
        TreeNode newNode = new TreeNode();
        newNode.Value = functionId;
        newNode.Text = strTest;
        tvMenu.ShowCheckBoxes = TreeNodeTypes.All;
        return newNode;
    }
    #endregion
    #region 用户权限查询
    private void loadMenuCheckbox()
    {
        //清理checkBox中的信息
        checkClear(tvMenu.Nodes);
        // string Id = Convert.ToString(ViewState["RoleID"]);
        System.Data.DataView dv = new System.Data.DataView((DataTable)Session["dt"]);
        foreach (DataRowView row in dv)
        {
            string FunctionID = row["FunctionID"].ToString();

            checkBoxcheck(tvMenu.Nodes, FunctionID);
        }

    }
    #endregion
    #region  清理checkBox中的信息
    private void checkClear(TreeNodeCollection prentNode)
    {
        foreach (TreeNode node in prentNode)
        {
            if (node.Checked == true)
            {
                node.Checked = false;
            }
            if (node.ChildNodes.Count > 0)
            {
                checkClear(node.ChildNodes);
            }
        }

    }
    #endregion

    #region 遍历树的节点信息，如果和查询的用户信息一致选树前的checkbox
    private void checkBoxcheck(TreeNodeCollection prentNode, string functionid)
    {
        //string UFunctionId = Convert.ToString(Session["FunctionId"].ToString());
        foreach (TreeNode node in prentNode)
        {
            string nodeValue = node.Value;
            if (functionid == nodeValue)
            {
                node.Checked = true;
                break;
            }
            if (node.ChildNodes.Count > 0)
            {
                checkBoxcheck(node.ChildNodes, functionid);
            }
        }
    }
    #endregion

    protected void btnSave_Click(object sender, EventArgs e)
    {
        bool message = true;
      //  EMS.DAL.TransactionManager transactionManager = new EMS.DAL.TransactionManager();
        DbTransaction trans= BLLFactory<T_Function2RoleManager>.Instance.CreateTransaction();
        try
        {

            //清空所以设置的权限    
            BLLFactory<T_Function2RoleManager>.Instance.DeleteByCondition(
                string.Format("RoleID='{0}'", ViewState["RoleID"].ToString()),trans);
            
            SaveFunction(tvMenu.Nodes, trans);
            
            // LoadMenu(tvMenu);
            trans.Commit();
            //Session.Remove("entity2func");
            message = true;
        }
        catch (Exception)
        {
            trans.Rollback();
            //ds.Tables["entity2func"].Clear();
            //Session["entity2func"] = ds;
        }
        if (message)
        {
        
            ScriptManager.RegisterClientScriptBlock(this.UpdatePanel1, this.GetType(), "a", "alert('保存成功！');", true);
        }
        else
        {
            ScriptManager.RegisterClientScriptBlock(this.UpdatePanel1, this.GetType(), "a", "alert('保存失败！');", true);
        }
    }
     private  void SaveFunction(TreeNodeCollection prentNode, DbTransaction trans)
     {
         foreach (TreeNode node in prentNode)
         {
             if (node.Checked == true)
             {
                 string nodeValue = node.Value;//树的节点Id
                 ViewState["nodeValue"] = nodeValue;//Id
                 T_Function2Role function2Role = new T_Function2Role();
                 function2Role.RoleID = int.Parse(ViewState["RoleID"].ToString());
                 function2Role.FunctionID = int.Parse(nodeValue);
                 BLLFactory<T_Function2RoleManager>.Instance.Insert(function2Role, trans);

             }
             if (node.ChildNodes.Count > 0)
             {
                 SaveFunction(node.ChildNodes, trans);
             }
         }
     }
    #region 判断树的那些节点被选中
    private void AddfuncBycheck(TreeNodeCollection prentNode, ref DataTable dt)
    {
        foreach (TreeNode node in prentNode)
        {
            if (node.Checked == true)
            {
                string nodeValue = node.Value;//树的节点Id
                ViewState["nodeValue"] = nodeValue;//Id
                DataRow row = dt.NewRow();
                row["RoleID"] = ViewState["RoleID"].ToString();
                row["FunctionID"] = nodeValue;
                dt.Rows.Add(row);

            }
            if (node.ChildNodes.Count > 0)
            {
                AddfuncBycheck(node.ChildNodes, ref dt);
            }
        }
    }
    #endregion
}